
package com.example.origin.spider.demo;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class CreditChinaSeleniumDemo {
    public static void main(String[] args) {
        System.getProperties().setProperty("webdriver.chrome.driver", "D:\\workspaces\\idea_workspaces\\origin_workspace\\origin\\origin-spider\\src\\main\\resources\\chromedriver.exe");
        List<String> list = new ArrayList<>();
//        list.add("headless");
//        list.add("disable-gpu");
        ChromeOptions options = new ChromeOptions();
        options.addArguments(list);

        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", "False");

        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-extensions");
        options.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0");
        ChromeDriver driver = new ChromeDriver(options);

//        ((JavascriptExecutor) driver).executeScript("Page.addScriptToEvaluateOnNewDocument","");

//        DevTools devTools = ((HasDevTools) driver).getDevTools();

        try {
            // 使用JavaScriptExecutor来执行JavaScript代码
            JavascriptExecutor jsExecutor = driver;

            // 执行JavaScript代码来修改window.navigator.webdriver的值
            String script =
                    "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})";
            jsExecutor.executeScript(script);

            // 可以再加一条检查语句确认webdriver属性是否被修改成功
            Boolean isWebDriverFlagModified = (Boolean) jsExecutor.executeScript("return window.navigator.webdriver === undefined");
            System.out.println("webdriver flag modified: " + isWebDriverFlagModified);

            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

            driver.get("https://www.creditchina.gov.cn/");
            Thread.sleep(5 * 1000);
            //获取当前页面的url
            String url = driver.getCurrentUrl();
            System.out.println(url);
            //获取当前页面的title
            String title = driver.getTitle();

            System.out.println(title);


        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            driver.quit();
        }

    }
}
